package com.github.ecbp.common.security.filter;

import com.alibaba.fastjson.JSON;
import com.github.ecbp.common.constant.CacheKeyConstant;
import com.github.ecbp.common.exception.user.NotLoginException;
import com.github.ecbp.common.security.config.JwtTokenConfig;
import com.github.ecbp.common.security.utils.CommonAdminUtils;
import com.github.ecbp.common.security.utils.JwtTokenUtil;
import com.github.ecbp.common.security.vo.DefaultUserDetails;
import com.github.ecbp.common.utils.IpAddressUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 */

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private JwtTokenConfig jwtTokenConfig;

    public UserDetails loadUserByLoginPhone(String username) {
        return CommonAdminUtils.getUserDetailsByLoginPhone(username, DefaultUserDetails.class);
    }

    /**
     * 1.获得token
     * 2.获得用户名,获得用户信息
     * 3.验证用户名, 验证token
     * 4.存储身份验证信息, 绑定到线程
     * 5.更新token失效时间
     *
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        //白名单请求直接放行
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String path : jwtTokenConfig.getUrls()) {
            if (pathMatcher.match(path, request.getRequestURI())) {
                chain.doFilter(request, response);
                return;
            }
        }

        String authToken = request.getHeader(jwtTokenUtil.getTokenHeader());
        if (!StringUtils.isEmpty(authToken)) {
            // 得到token中的loginPhone
            String loginPhone = jwtTokenUtil.getLoginPhoneFromToken(authToken);
            if (loginPhone != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 对比redis中的token和请求头中的token
                String tokenInRedis = jwtTokenUtil.getTokenFromRedis(loginPhone);
                if (StringUtils.isEmpty(tokenInRedis)) {
                    tokenInRedis = jwtTokenUtil.getTokenFromRedis(loginPhone, CacheKeyConstant.APPLET);
                }
                if (!StringUtils.isEmpty(tokenInRedis) && tokenInRedis.equals(authToken)) {
                    // 对比token中的loginPhone和库中loginPhone
                    UserDetails userDetails = this.loadUserByLoginPhone(loginPhone);
                    if (null != userDetails && jwtTokenUtil.validateToken(authToken, userDetails)) {
                        // 存储身份验证信息
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        LOGGER.info("[ token验证通过 账号: {}]", loginPhone);
                        SecurityContextHolder.getContext().setAuthentication(authentication);

                        // 更新token失效时间
                        jwtTokenUtil.setTokenToRedis(loginPhone, authToken);
                    }
                } else {
                    LOGGER.info("[ token验证失败 loginPhone: {}, 未登录或token不一致 ]", loginPhone);
                }
            }
        }
        chain.doFilter(request, response);
    }
}